<?php
    class Admincp_NewsController extends Main_Controller_Action
    {
        private $_arrParam;
        private $_model;
        private $_validate;
        
        public function init()
        {
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
            $this->_model = new Admincp_Model_News();
            $this->_validate = new Admincp_Form_ValidateNews();
            $this->view->headTitle('Quản lý tin tức');
        }
        
        public function preDispatch()
        {
            $auth = Zend_Auth::getInstance();
            if(!$auth->hasIdentity()) {
                if($this->_request->getActionName() != 'login')
                    $this->_redirect('admincp/index/login');
            }
        }
        
        public function indexAction()
        {
            $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->listItem());
			$paginator = new Zend_Paginator($adapter);
			$paginator->setItemCountPerPage(40);
			$paginator->setPageRange(5);
			$currentPage = $this->_request->getParam('page', 1);
			$paginator->setCurrentPageNumber($currentPage);
			$this->view->data = $paginator;
			$this->view->total = $paginator->getTotalItemCount();
            
            if($_POST['add']) {
                $this->_redirect('admincp/news/create');
            }
            if($_POST['delete']) {
                $listId = $this->_arrParam['check'];
			    $this->_model->deleteMultiItem($listId);
			    $this->_redirect($_SERVER['HTTP_REFERER']);
            }
        }
        
        public function createAction()
        {
            if($this->_request->isPost()) {
                $title = trim(strip_tags($this->_arrParam['title']));
                $description = trim($this->_arrParam['description']);
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $image = $upload->getFileName('image', false);
                $flag = true;
                
                $upload->addValidator('Size', false, 4800000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                if(!$upload->isValid()) {
                    $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                    $flag = false;
                }
                if(!$this->_validate->validImage($image)) {
                    $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                    $flag = false;
                }
                if($this->_validate->validTitle($title)) {
                    $this->view->titleValue = $title;
                }
                else {
                    $this->view->errorTitle = 'Tiêu đề có độ dài 1-300 kí tự';
                    $flag = false;
                }
                if($this->_validate->validDescription($description)) {
                    $this->view->descriptionValue = $description;
                }
                else {
                    $this->view->errorDescription = 'Nội dung không được để trống';
                    $flag = false;
                }
                
                if($flag == true) {
                    $resize = new Zend_Filter_ImageSize();
                    preg_match('#\.([^\.]+)$#', $image, $matches);
                    $fileExtension  = $matches[1];
                    $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                    $newFileName1 = $fileName . '.' . $fileExtension;
                    $options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName1,'overwrite'=>true);
                    $upload->addFilter('Rename',$options,'image');
                    $upload->receive('image');
                    $output = $resize->setHeight(250)
                                    ->setWidth(250)
                                    ->setThumnailDirectory(BASE_PATH . '/public/files/news/')
                                    ->filter(BASE_PATH . '/public/files/news/' . $newFileName1);
                    header('Content-Type: image/jpeg');
                    $fh = fopen($output, 'r');
                    fpassthru($fh);
                    fclose($fh);
                    $newFileName = $fileName . '-250x250.' . $fileExtension;
                    unlink(PUBLIC_PATH . '/files/news/' . $newFileName1);

                    $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $common = new Admincp_Model_Common();
                    $create_date = date('Y-m-d');
                    $data = array(
                        'title' => $title,
                        'image' => $newFileName,
                        'description' => $description,
                        'short_description' => $common->cut_string(strip_tags($description), 500, 1),
                        'create_date' => $create_date,
                        'url' => $strFlex->filter2(strtolower($title)),
                        'status' => 1,
                    );
                    $this->_model->saveItem($data, 'create');
                    $this->_redirect('admincp/news');
                }
            }
        }
        
        public function editAction()
        {
            $id = (int) $this->_arrParam['id'];
            $this->view->data = $this->_model->getItem($id);
            
            if($this->_request->isPost()) {
                $title = trim(strip_tags($this->_arrParam['title']));
                $description = trim($this->_arrParam['description']);
                $upload = new Zend_File_Transfer_Adapter_Http();
                $info = $upload->getFileInfo();
                $image = $upload->getFileName('image', false);
                $flag = true;
                
                if(!$this->_validate->validTitle($title)) {
                    $this->view->errorTitle = 'Tiêu đề có độ dài 1-300 kí tự';
                    $flag = false;
                }
                if(!$this->_validate->validDescription($description)) {
                    $this->view->errorDescription = 'Nội dung không được để trống';
                    $flag = false;
                }
                
                if($flag == true) {
                    $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $common = new Admincp_Model_Common();
                    $create_date = date('Y-m-d');
                    $data = array(
                        'id' => $id,
                        'title' => $title,
                        'description' => $description,
                        'short_description' => $common->cut_string(strip_tags($description), 500, 1),
                        'create_date' => $create_date,
                        'url' => $strFlex->filter2(strtolower($title)),
                    );
                    if($this->_validate->validImage($image)) {
                        $upload->addValidator('Size', false, 4800000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                        if(!$upload->isValid()) {
                            $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                        }
                        else {
                            $resize = new Zend_Filter_ImageSize();
                            preg_match('#\.([^\.]+)$#', $image, $matches);
                            $fileExtension  = $matches[1];
                            $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                            $newFileName1 = $fileName . '.' . $fileExtension;
                            $options = array('target' => BASE_PATH . '/public/files/news/' . $newFileName1,'overwrite'=>true);
                            $upload->addFilter('Rename',$options,'image');
                            $upload->receive('image');
                            $output = $resize->setHeight(250)
                                            ->setWidth(250)
                                            ->setThumnailDirectory(BASE_PATH . '/public/files/news/')
                                            ->filter(BASE_PATH . '/public/files/news/' . $newFileName1);
                            header('Content-Type: image/jpeg');
                            $fh = fopen($output, 'r');
                            fpassthru($fh);
                            fclose($fh);
                            $newFileName = $fileName . '-250x250.' . $fileExtension;
                            unlink(PUBLIC_PATH . '/files/news/' . $newFileName1);
                            
                            $data['image'] = $newFileName;
                            $this->_model->saveItem($data, 'update');
                            if(is_file(PUBLIC_PATH . '/files/news/' . $this->view->data['image'])) {
  								@unlink(PUBLIC_PATH . '/files/news/' . $this->view->data['image']);
   							}
                            $this->_redirect('admincp/news');
                        }
                    }
                    else {
                        $this->_model->saveItem($data, 'update');
                        $this->_redirect('admincp/news');
                    }
                }
            }
        }
        
        public function deleteAction()
        {
            $id = (int) $this->_arrParam['id'];
		    $this->_model->deleteItem($id);
		    $this->_redirect($_SERVER['HTTP_REFERER']);
        }
        
        public function publishAction()
		{
		    $id = (int) $this->_arrParam['id'];
		    $status = (int) $this->_arrParam['status'];
		    $status = ($status == 1) ? 2 : 1;
		    $data = array(
                'id' => $id,
		        'status' => $status,
		    );
		    $this->_model->saveItem($data, 'update');
		    $this->_redirect($_SERVER['HTTP_REFERER']);
		}
        
        public function searchAction()
		{
		    $strFlex = new Zendvn_Filter_RemoveCircumflex();
		    $title = strtolower(trim($strFlex->filter(strip_tags($this->_arrParam['title']))));
		    $status = (int) $this->_arrParam['status'];
            $start_date = trim(strip_tags($this->_arrParam['start_date']));
		    $end_date = trim(strip_tags($this->_arrParam['end_date']));
		    $this->view->keyword = array(
	            'title' => $this->_arrParam['title'],
	            'status' => $this->_arrParam['status'],
	            'start_date' => $this->_arrParam['start_date'],
	            'end_date' => $this->_arrParam['end_date'],
		    );
		    $data = array(
	            'title' => (string) '%'.str_replace(' ','%',$title).'%',
	            'start_date' => $start_date,
	            'end_date' => $end_date,
	            'status' => $status,
		    );
		    $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->searchItem($data));
		    $paginator = new Zend_Paginator($adapter);
		    $paginator->setItemCountPerPage(40);
		    $paginator->setPageRange(5);
		    $currentPage = $this->_request->getParam('page', 1);
		    $paginator->setCurrentPageNumber($currentPage);
		    $this->view->data = $paginator;
		    $this->view->total = $paginator->getTotalItemCount();
		}
    }
